using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Application.Service.Mp;
using Admin.NET.Core;
using Furion.DependencyInjection;
using Furion.EventBus;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;

namespace Admin.NET.Application.EventBus;

/// <summary>
/// 公众号推送消息订阅，类型3
/// </summary>
public class MpOpenEventSubscribe : IEventSubscriber, ISingleton, IPrivateDependency
{
	private readonly IServiceProvider _serviceProvider;

	public MpOpenEventSubscribe(IServiceProvider serviceProvider)
	{
		_serviceProvider = serviceProvider;
	}

	/// <summary>
	/// 发送通知站内信（自定义账单催缴）
	/// </summary>
	/// <param name="context"></param>
	/// <returns></returns>
	[EventSubscribe("3:SendBillNotice")]
	public async Task SendNotice(EventHandlerExecutingContext context)
	{
		using IServiceScope scope = _serviceProvider.CreateScope();
		SqlSugarRepository<CustomRoomBill> _rep = scope.ServiceProvider.GetRequiredService<SqlSugarRepository<CustomRoomBill>>();
		EventPayload payload = (EventPayload)context.Source.Payload;
		BillNoticePayload gateNotice = JsonConvert.DeserializeObject<BillNoticePayload>(payload.Data);
		MpOpenService mpservice = scope.ServiceProvider.GetRequiredService<MpOpenService>();
		if (gateNotice.Owners == null || gateNotice.Owners.Count <= 0)
		{
			return;
		}
		List<long> ownerids = gateNotice.Owners.Select((Owner s) => s.Id).ToList();
		List<CustomRoomBill> bills = await _rep.GetListAsync((CustomRoomBill u) => u.TenantId == (long?)payload.TenantId && u.BillTemplateId == gateNotice.BillTemplateId && u.OwnerId != null && ownerids.Contains((long)u.OwnerId));
		foreach (Owner owner in gateNotice.Owners)
		{
			mpservice.SendCustomBillTemplate(amount: bills.Where((CustomRoomBill w) => w.OwnerId == owner.Id).SelectMany((CustomRoomBill m) => m.Bills).Sum((CustomBill s) => s.Fee) + "元", method: (gateNotice.CallRules == 0L) ? "断电催缴" : ((gateNotice.CallRules == 1) ? "限制缴费" : ((gateNotice.CallRules == 2) ? "余额抵扣" : "")), billName: "自定账单", status: "待缴费", endTime: gateNotice.EndDate, ownerId: owner.Id).Wait();
		}
	}

	/// <summary>
	/// 电表被拉合闸时的消息通知
	/// </summary>
	/// <param name="context"></param>
	/// <returns></returns>
	[EventSubscribe("3:SendGateNotice")]
	public async Task SendGateNotice(EventHandlerExecutingContext context)
	{
		using IServiceScope scope = _serviceProvider.CreateScope();
		scope.ServiceProvider.GetRequiredService<SqlSugarRepository<OwnerNotice>>();
		EventPayload payload = (EventPayload)context.Source.Payload;
		BillNoticePayload gateNotice = JsonConvert.DeserializeObject<BillNoticePayload>(payload.Data);
		MpOpenService mpservice = scope.ServiceProvider.GetRequiredService<MpOpenService>();
		if (gateNotice.Owners != null && gateNotice.Owners.Count > 0)
		{
			Owner owner = gateNotice.Owners[0];
			if (gateNotice.GateStatus == 1)
			{
				await mpservice.SendPowerOffSuccessTemplate(gateNotice.RoomName, owner.Id);
			}
			else
			{
				await mpservice.SendPowerOnSuccessTemplate(gateNotice.RoomName, owner.Id);
			}
		}
	}

	/// <summary>
	/// 支付结果通知
	/// </summary>
	/// <param name="context"></param>
	/// <returns></returns>
	[EventSubscribe("3:SendPaymentNotice")]
	public async Task SendPaymentNotice(EventHandlerExecutingContext context)
	{
		using IServiceScope scope = _serviceProvider.CreateScope();
		SqlSugarRepository<Room> _rep = scope.ServiceProvider.GetRequiredService<SqlSugarRepository<Room>>();
		EventPayload payload = (EventPayload)context.Source.Payload;
		BillNoticePayload gateNotice = JsonConvert.DeserializeObject<BillNoticePayload>(payload.Data);
		MpOpenService mpservice = scope.ServiceProvider.GetRequiredService<MpOpenService>();
		if (gateNotice.Owners != null && gateNotice.Owners.Count > 0)
		{
			Owner owner = gateNotice.Owners[0];
			decimal balance = await (from w in _rep.AsQueryable()
				where w.TenantId == (long?)payload.TenantId && w.Id == gateNotice.RoomId
				select w.Balance).FirstAsync();
			await mpservice.SendPaySuccessTemplate(owner.Id, owner.PhoneNumber, gateNotice.Amount, balance + "元", gateNotice.OrderNo);
		}
	}

	/// <summary>
	/// 余额提前预警
	/// </summary>
	/// <param name="context"></param>
	/// <returns></returns>
	[EventSubscribe("3:SendEarlyWarningNotice")]
	public async Task SendEarlyWarningNotice(EventHandlerExecutingContext context)
	{
		using IServiceScope scope = _serviceProvider.CreateScope();
		scope.ServiceProvider.GetRequiredService<SqlSugarRepository<Room>>();
		EventPayload payload = (EventPayload)context.Source.Payload;
		BillNoticePayload gateNotice = JsonConvert.DeserializeObject<BillNoticePayload>(payload.Data);
		MpOpenService mpservice = scope.ServiceProvider.GetRequiredService<MpOpenService>();
		if (gateNotice.Owners != null && gateNotice.Owners.Count > 0)
		{
			await mpservice.SendBalanceTemplate(ownerId: gateNotice.Owners[0].Id, roomName: gateNotice.RoomName, roomId: gateNotice.RoomId, amount: gateNotice.Balance + "元");
		}
	}
}
